package com.mef.smsplat.web.controller.sys.group;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.hc24.util.IDUtil;
import com.mef.smsplat.dao.base.DataGridModel;
import com.mef.smsplat.dao.base.Page;
import com.mef.smsplat.domain.PersonInfoDomain;
import com.mef.smsplat.exception.BusinessException;
import com.mef.smsplat.service.PersonInfoService;
import com.mef.smsplat.util.Constants;
import com.mef.smsplat.web.controller.base.Json;

@Controller
@RequestMapping("/sys/passenger")
public class PersonInfoController {
	private PersonInfoService personInfoService;

	public void setPersonInfoService(PersonInfoService personInfoService) {
		this.personInfoService = personInfoService;
	}

	@ResponseBody
	@RequestMapping("/query.sys")
	public Page<PersonInfoDomain> query(String personName, String personNi,
			String personPhone, String groupId,DataGridModel dgm) {
		return personInfoService.query(personName, personNi, personPhone,groupId, dgm);
	}

	@ResponseBody
	@RequestMapping("/add.sys")
	public Json add(PersonInfoDomain person) {
		if (person.getPersonName() == null
				|| "".equals(person.getPersonName().trim())) {
			throw new BusinessException("姓名不能为空");
		}
		if (person.getPersonPhone() == null || "".equals(person.getPersonPhone().trim())) {
			throw new BusinessException("联系电话不能为空");
		}
		if (!personInfoService.isUnique(person.getPersonPhone(), person.getPersonId())) {
			throw new BusinessException("此联系电话已经存在");
		}

		person.setPersonId(IDUtil.next() + "");
		personInfoService.save(person);
		return new Json();
	}

	@ResponseBody
	@RequestMapping("/update.sys")
	public Json update(PersonInfoDomain person) {
		if (person.getPersonName() == null
				|| "".equals(person.getPersonName().trim())) {
			throw new BusinessException("姓名不能为空");
		}
		if (person.getPersonPhone() == null || "".equals(person.getPersonPhone().trim())) {
			throw new BusinessException("联系电话不能为空");
		}
		if (!personInfoService.isUnique(person.getPersonPhone(), person.getPersonId())) {
			throw new BusinessException("此联系电话已经存在");
		}
		personInfoService.update(person);
		return new Json();
	}

	@ResponseBody
	@RequestMapping("/del.sys")
	public Json del(String[] ids) {
		//删除person记录
		personInfoService.removeById(ids);
		//删除person group记录
		personInfoService.deleteRelateGroup(ids);
		return new Json();
	}

	@ResponseBody
	@RequestMapping("/importFile.sys")
	public Json importFile(HttpServletRequest request, String fileType){
		Json json= new Json();
		MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> map = multipart.getFileMap();
		Iterator<String> it = map.keySet().iterator();
		while (it.hasNext()) {
			MultipartFile file = map.get(it.next());
			if (file == null || file.isEmpty()) {
				json.setSuccess(false);
				json.setMsg("请选择导入文件");
				return json;
			}
			try {
				ArrayList<PersonInfoDomain> persons = null;
				if ((Constants.TXT + "").equals(fileType)) {
					persons = getPersonsByTxt(file);
				}else if((Constants.EXCEL + "").equals(fileType)) {
					persons = getPersonsByExcel(file);
				}
				for(PersonInfoDomain person:persons){
					personInfoService.save(person);
				}
			} catch (Exception e) {
				json.setSuccess(false);
				json.setMsg(e.getMessage());
				return json;
			}
		}
		return json;
	}
	
	@ResponseBody
	public ArrayList<PersonInfoDomain> getPersonsByTxt(MultipartFile file){
		ArrayList<PersonInfoDomain> persons = new ArrayList<PersonInfoDomain>();
		if (!file.getOriginalFilename().toLowerCase().endsWith(".txt"))throw new BusinessException("请上传txt格式文件");
		byte[] tmpByte = new byte[(int) file.getSize()];
		try {
			tmpByte = file.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String tmpContent = new String(tmpByte);
		String[] lines = tmpContent.replaceAll("\r", "").split("\n");
		for (int i = 0; i < lines.length; i++) {
			System.out.println(lines[i]);
			String[] infos = lines[i].split(",");
			PersonInfoDomain person = new PersonInfoDomain();
			person.setPersonId(IDUtil.next() + "");
			if(infos[0]==null || "".equals(infos[0].trim())){
				throw new BusinessException("第"+(i+1)+"行姓名不能为空");
			}else{
				person.setPersonName(infos[0]);
			}
			if (infos[1].equals("男")) {
				person.setPersonSex(Constants.MALE);
			} else if(infos[1].equals("女")){
				person.setPersonSex(Constants.FEMALE);
			}else{
				throw new BusinessException("第"+(i+1)+"行性别不合法");
			}
			if(infos[2]==null || "".equals(infos[2])){
				throw new BusinessException("第"+(i+1)+"行电话不能为空");
			}else{
				person.setPersonPhone(infos[2]);
			}
			if (!personInfoService.isUnique(infos[2], person.getPersonId())) {
				throw new BusinessException("第"+(i+1)+"行联系电话" + infos[2] + "已经存在");
			}
			person.setPersonNi(infos[3]);
			if (infos[4].equals("旅客")) {
				person.setPersonType(Constants.PASSENGER);
			} else if(infos[4].equals("工作人员")){
				person.setPersonType(Constants.WORKMAN);
			}else{
				throw new BusinessException("第"+(i+1)+"行人员类型不合法(请输入旅客或工作人员)");
			}
			person.setRemark(infos[5]);
			persons.add(person);
		}
		return persons;
	}
	
	@ResponseBody
	public ArrayList<PersonInfoDomain> getPersonsByExcel(MultipartFile file){
		ArrayList<PersonInfoDomain> persons = new ArrayList<PersonInfoDomain>();
		if (!(file.getOriginalFilename().endsWith(".xls") || file.getOriginalFilename().endsWith(".xlsx")))
			throw new BusinessException("请上传excel格式文件");
		Workbook wb = null;
		try {
			wb = Workbook.getWorkbook(file.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 获得第一页的Sheet
		Sheet sheet = wb.getSheet(0);
		// 获取各行各列的值
		for(int row = 0;row < sheet.getRows(); row++){
			PersonInfoDomain person = new PersonInfoDomain();
			person.setPersonId(IDUtil.next() + "");
			for(int col = 0; col <= 5; col++){
				Cell[] cells = sheet.getRow(row);
				if(cells[0].getContents()==null || "".equals(cells[0].getContents())){
					throw new BusinessException("第"+(row+1)+"行姓名不能为空");
				}else{
					person.setPersonName(cells[0].getContents());
				}
				if (cells[1].getContents().equals("男")) {
					person.setPersonSex(Constants.MALE);
				} else if(cells[1].getContents().equals("女")){
					person.setPersonSex(Constants.FEMALE);
				}else{
					throw new BusinessException("第"+(row+1)+"行性别不合法");
				}

				if (!personInfoService.isUnique(cells[2].getContents(), person.getPersonId())) {
					throw new BusinessException("第"+(row+1)+"行联系电话" + cells[2].getContents() + "已经存在");
				}
				if(cells[2].getContents()==null || "".equals(cells[2].getContents())){
					throw new BusinessException("第"+(row+1)+"行电话不能为空");
				}else{
					person.setPersonPhone(cells[2].getContents());
				}
				person.setPersonNi(cells[3].getContents());
				if (cells[4].getContents().equals("旅客")) {
					person.setPersonType(Constants.PASSENGER);
				} else if(cells[4].getContents().equals("工作人员")) {
					person.setPersonType(Constants.WORKMAN);
				}else{
					throw new BusinessException("第"+(row+1)+"行人员类型不合法(请输入旅客或工作人员)");
				}
				person.setRemark(cells[5].getContents());
			}
			persons.add(person);
		}
		// 关闭文件
		wb.close();
		return persons;
	}

}
